package com.ybwh.springboot2.conf;

import com.ybwh.springboot2.common.RespData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @Description: 后台返回数据统一全局处理
 * @Author: sunzhaoxiang
 * @Date: 2018/7/4 下午12:59
 */
@Slf4j
//@ControllerAdvice(basePackages = "com.ybwh.springboot2")
public class GlobalResponseHandler implements ResponseBodyAdvice<Object> {

    /**
     * @Description: 判断需要支持的类型
     * @Author: sunzhaoxiang
     * @Date: 2018/7/4 下午1:01
     */
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        final String returnTypeName = returnType.getParameterType().getName();
        return !RespData.class.getName().equals(returnTypeName) || ResponseEntity.class.getName().equals(returnTypeName);
    }

    /**
     * @Description: 统一处理返回数据
     * @Author: sunzhaoxiang
     * @Date: 2018/7/4 下午1:01
     */
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType
            , MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType
            , ServerHttpRequest request, ServerHttpResponse response) {
        final String returnTypeName = returnType.getParameterType().getName();
        if ("void".equals(returnTypeName) || "String".equals(returnTypeName)) {
            return body;
        }
        return RespData.successResp(body);
    }
}
